// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

const serialPort = require("serialport")
//获取到的所有串口
var serialPorts
//选中的串口
var port
//连接按钮
var btnConnect = $("#btnConnect")
//select
var selectSerial = $("#select_serial")

//将需要发送的16进制字符串分割成数组
var wholeArray
//发送位置
var position
//正在发送的字符串
var sendStr
//真正发送的字符串长度
// var sendDataLen

initSerialPort()

function initSerialPort() {
    serialPort.list(function (err, ports) {
        if (!err) {
            serialPorts = ports
            selectSerial.empty()
            ports.forEach(function (port) {
                selectSerial.append(
                    `<option value='${port.comName}'>${port.comName}</option>`
                )
            })
        } else {
            showAlert(err)
        }
    })

    $("#btnSend").click(function () {
        writeOperation("123456789")
    })

    btnConnect.click(function () {
        setBtnEnabled(false)
        if (!port) {
            initPort()
        }
        if (!port) {
            showAlert("请插入串口设备并重启应用")
            setBtnEnabled(true)
            return
        }
        if (btnConnect.text() === "连接") {
            port.open(function (err) {
                setBtnEnabled(true)
                if (err) {
                    console.log(`open error ${err}`)
                    showAlert(err)
                } else {
                    console.log('open suc')
                    btnConnect.text("断开连接")
                    setSelectEnabled(false)
                    port.on("data", function (data) {
                        console.log(`new value ${data}`)
                        if (position < wholeArray.length) {
                            delaySend()
                        } else {
                            hideLoading()
                        }
                    })
                }
            })
        } else {
            port.close(function (err) {
                setBtnEnabled(true)
                if (err) {
                    console.log(`close error ${err}`)
                    showAlert(err)
                } else {
                    console.log('close suc')
                    btnConnect.text("连接")
                    setSelectEnabled(true)
                    port = null
                }
            })
        }
    })

    selectSerial.change(function () {
        initPort()
    })
}

function writeOperation(code) {
    if (!port) {
        showAlert("请连接串口设备")
    } else {
        writeToDevice(code)
    }
}

function initPort() {
    if (getSelectPort()) {
        port = new serialPort(getSelectPort().comName, {
            baudRate: 115200,
            autoOpen: false
        })
    }
}

function writeToDevice(code) {
    showLoading()
    let wholeStr = getSendStr(code)
    wholeArray = wholeStr.split("0a")
    for (let i = 0; i < wholeArray.count; i++) {
        if (i === 0) {
            wholeArray[i] = wholeArray[i] + "03"
        } else {
            wholeArray[i] = wholeArray[i] + "0a"
        }
    }
    position = 0
    delaySend()
}

function delaySend() {
    let time
    if (position === 0) {
        time = 1
    } else if (position === 1) {
        time = 1500
    } else {
        time = 1000
    }
    setTimeout(function () {
        sendStr = wholeArray[position]
        // sendDataLen = sendStr.length
        if (sendStr) {
            onSend()
        }
    }, time)
}

function onSend() {
    port.write(str2Bytes(sendStr), writeEvent)
    position++
    let percentStr = (position * 100 / wholeArray.length).toPrecision(12) + "%"
    console.log(`percentStr: ${percentStr}`)
    $(".progress-bar").css("width", percentStr)
}

const writeEvent = function (err) {
    if (err) {
        hideLoading()
        showAlert(err)
        console.log(err)
    }
}

/**
 * 包装命令
 * @param originStr 原始命令
 * @return 包装后硬件可以识别的命令
 */
function getSendStr(originStr) {
    var reg = /\n/g
    originStr = originStr.replace(reg, "\\n")
    console.log(`myOriginStr: ${originStr}`)
    var targetStr = `030a${addPostfixTo16("f=open('/flash/main.py', 'w')")}`
    var commandStr = `f.write('import kq\\n${originStr}\\n')\r\n`
    targetStr = `${targetStr}${addPostfixTo16(commandStr)}${addPostfixTo16("f.close()")}04`
    return targetStr;
}

/**
 * 将字符串转化为16进制并在后面加上回车换行
 *
 * @param s 原始字符串
 * @return string 加换行后的字符串
 */
function addPostfixTo16(s) {
    return `${stringToHex(s)}0d0a`
}

function stringToHex(str) {
    var val = "";
    for (var i = 0; i < str.length; i++) {
        if (val === "")
            val = str.charCodeAt(i).toString(16);
        else
            val += str.charCodeAt(i).toString(16);
    }
    return val;
}

function hexToString(str) {
    var val = "";
    var arr = str.split(",");
    for (let i = 0; i < arr.length; i++) {
        val += arr[i].fromCharCode(i);
    }
    return val;
}

function showLoading() {
    $("#loading").css("display", "block")
}

function hideLoading() {
    $(".progress-bar").css("width", "0%")
    $("#loading").css("display", "none")
}

function setBtnEnabled(enabled) {
    if (enabled) {
        btnConnect.attr("class", "abled")
        btnConnect.attr('disabled', false)
    } else {
        btnConnect.attr("class", "disabled")
        btnConnect.attr('disabled', true)
    }
}

function setSelectEnabled(enabled) {
    if (enabled) {
        selectSerial.attr('disabled', false)
    } else {
        selectSerial.attr('disabled', true)
    }
}

function getSelectPort() {
    for (var i = 0; i < serialPorts.length; i++) {
        if (serialPorts[i].comName === selectSerial.val()) {
            return serialPorts[i]
        }
    }
}

function showAlert(content) {
    alert(content)
}

function showConfirm(content, confirmFunc, cancelFunc) {
    let confirm = confirm(content)
    if (confirm === true) {
        confirmFunc()
    } else {
        cancelFunc()
    }
}

module.exports = {
    writeOperation
}


//十六进制字符串转字节数组
function str2Bytes(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 !== 0) {
        return null;
    }
    len /= 2;
    var hexA = [];
    for (var i = 0; i < len; i++) {
        var s = str.substr(pos, 2);
        var v = parseInt(s, 16);
        hexA.push(v);
        pos += 2;
    }
    return hexA;
}

